<template>
  <div>
    <div class="toolbar">
      <el-select v-model="studentId" placeholder="学生" filterable clearable style="width: 220px">
        <el-option v-for="s in studentOptions" :key="s.id" :label="`${s.studentNo} - ${s.name}`" :value="s.id" />
      </el-select>
      <el-select v-model="offeringId" placeholder="开课" filterable clearable style="width: 240px">
        <el-option v-for="o in offeringOptions" :key="o.id" :label="`开课#${o.id} 课程${o.courseId} 班级${o.classId} 学期${o.termId}`" :value="o.id" />
      </el-select>
      <el-button type="primary" @click="load">查询选课</el-button>
      <el-button type="success" @click="openCreate">新增选课</el-button>
    </div>

    <el-table :data="items" stripe style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="studentId" label="学生ID" width="110" />
      <el-table-column prop="offeringId" label="开课ID" width="110" />
      <el-table-column prop="status" label="状态" width="160" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-popconfirm title="确认删除该选课记录？" @confirm="doDelete(row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="新增选课" width="560">
      <el-form :model="form" label-width="100px">
        <el-form-item label="学生">
          <el-select v-model="form.studentId" placeholder="选择学生" filterable style="width: 240px">
            <el-option v-for="s in studentOptions" :key="s.id" :label="`${s.studentNo} - ${s.name}`" :value="s.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="开课">
          <el-select v-model="form.offeringId" placeholder="选择开课" filterable style="width: 240px">
            <el-option v-for="o in offeringOptions" :key="o.id" :label="`开课#${o.id} 课程${o.courseId} 班级${o.classId} 学期${o.termId}`" :value="o.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="选择">
            <el-option label="在读" value="ENROLLED" />
            <el-option label="重修" value="RETAKE" />
            <el-option label="免修" value="EXEMPT" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { listEnrollments, createEnrollment, deleteEnrollment, type Enrollment } from '@/api/grades/enrollments'
import { listStudents, type Student } from '@/api/grades/students'
import { listOfferings, type CourseOffering } from '@/api/grades/offerings'

const loading = ref(false)
const items = ref<Enrollment[]>([])
const studentId = ref<number | undefined>(undefined)
const offeringId = ref<number | undefined>(undefined)

const dialogVisible = ref(false)
const form = ref<Enrollment>({ status: 'ENROLLED' })

const studentOptions = ref<Student[]>([])
const offeringOptions = ref<CourseOffering[]>([])

async function load() {
  loading.value = true
  try {
    items.value = await listEnrollments({ studentId: studentId.value, offeringId: offeringId.value })
  } finally {
    loading.value = false
  }
}

function openCreate() {
  form.value = { status: 'ENROLLED', studentId: studentId.value, offeringId: offeringId.value }
  dialogVisible.value = true
}

async function submit() {
  try {
    await createEnrollment(form.value)
    ElMessage.success('创建成功')
    dialogVisible.value = false
    await load()
  } catch (e: any) {
    ElMessage.error(e?.message || '操作失败')
  }
}

async function doDelete(id?: number) {
  if (!id) return
  try {
    await deleteEnrollment(id)
    ElMessage.success('已删除')
    await load()
  } catch (e: any) {
    ElMessage.error(e?.message || '删除失败')
  }
}

async function loadStudentOptions() {
  try {
    const res = await listStudents({ offset: 0, limit: 1000 })
    studentOptions.value = res.items
  } catch {}
}

async function loadOfferingOptions() {
  try {
    offeringOptions.value = await listOfferings({})
  } catch {}
}

onMounted(() => {
  loadStudentOptions()
  loadOfferingOptions()
})
</script>

<style scoped>
.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
}
</style>